package com.purong.purong.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.github.mikephil.charting.animation.Easing;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.formatter.PercentFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.purong.purong.Contant;
import com.purong.purong.PermissionConstant;
import com.purong.purong.PuRongApp;
import com.purong.purong.R;
import com.purong.purong.adapter.BankLoanConditionAdapter;
import com.purong.purong.adapter.BankLoanMaterAdapter;
import com.purong.purong.adapter.LoanDetQuestionAdapter;
import com.purong.purong.adapter.LoanQuestionAdapter;
import com.purong.purong.bean.BankLoanDetBean;
import com.purong.purong.bean.BankLoanApplyBean;
import com.purong.purong.bean.BankLoanBean;
import com.purong.purong.bean.QuestionBean;
import com.purong.purong.bean.BankLoanQuestListBean;
import com.purong.purong.bean.PeriodBean;
import com.purong.purong.util.CommonUtil;
import com.purong.purong.util.ComputeUtil;
import com.purong.purong.util.SharePreUtil;
import com.purong.purong.widget.AdjustSizeRelativeLayout;
import com.purong.purong.widget.FullyLinearLayoutManager;
import com.purong.purong.widget.GradationScrollView;
import com.purong.purong.widget.LoadingView;
import com.purong.purong.widget.PeriodDialog;
import com.purong.purong.widget.RadiusImageView;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.yao.sdk.glide.GlideUtil;
import com.yao.sdk.net.ResponseInfo;
import com.yaoming.umengshare.SharePlatform;
import com.yaoming.umengshare.UmShare;
import com.yaoming.umengshare.listener.ShareResultListener;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import me.grantland.widget.AutofitTextView;

/**
 * Created by wenjiezeng on 2017/11/1.
 */
public class BankLoanDetialActivity extends BasePermActivity implements OnChartValueSelectedListener, GradationScrollView.ScrollViewListener {

    private RadiusImageView loanImg;
    private PieChart mPieChart;
    private AdjustSizeRelativeLayout mainLay;
    private GradationScrollView mScrollView;
    private RelativeLayout titleBar;
    private ImageView back;
    private ImageView flowImg, favoriteImg, editImg;
    private View titleCutLine;
    private EditText loanMoneyEd;
    private AutofitTextView moneyRate;
    private TextView title, periodTv, loanName, loanNote, tagOne, tagTwo, tagThree, totalRate, loanInfo,
            loanRate, loanFee, loanOnetime;
    private RecyclerView conditRecyclerView;
    private RecyclerView mateRecyclerView;
    private RecyclerView questRecyclerView;
    private BankLoanConditionAdapter mConditAdapter;
    private BankLoanMaterAdapter mMaterAdapter;
    private LoanDetQuestionAdapter mQuestAdapter;
    private List<String> conditList = new ArrayList<>();
    private List<String> materList = new ArrayList<>();
    private List<QuestionBean> questList = new ArrayList<>();
    private int titlebarRange, titleTxRange;
    private PeriodDialog mPeriodDialog;
    private List<PeriodBean> periodList = new ArrayList<>();
    private PeriodBean mPeriod;
    private BankLoanBean mLoan;
    private BankLoanDetBean loanDetBean;
    private LoadingView mLoadingView;
    private boolean needBack;

    @Override
    public void finish() {
        if (needBack && loanDetBean != null) {
            Intent intent = new Intent();
            intent.putExtra("LOAN", loanDetBean);
            setResult(RESULT_OK, intent);
        }
        super.finish();
    }

    @Override
    public void initView() {

        mLoadingView = (LoadingView) findViewById(R.id.loading_view);
        mLoadingView.setLoadListener(new LoadingView.OnLoadListener() {
            @Override
            public void onReload() {
                if (mLoan != null) {
                    getLoanDet();
                    getQuestion();
                }
            }

            @Override
            public void onRefresh() {

            }
        });
        mainLay = (AdjustSizeRelativeLayout) findViewById(R.id.main_lay);
        mainLay.setSoftKeyBoardListener(new AdjustSizeRelativeLayout.SoftkeyBoardListener() {
            @Override
            public void keyBoardVisable(int move) {
                editImg.setVisibility(View.INVISIBLE);
                Log.e("zwj", "..键盘弹出");
            }

            @Override
            public void keyBoardInvisable(int move) {
                editImg.setVisibility(View.VISIBLE);
                String loanString = loanMoneyEd.getText().toString().trim();
                if (loanString.endsWith("."))
                    loanString = loanString.replaceAll("\\.", "");
                if (loanString == null || loanString.equals("") ||
                        Double.valueOf(loanString) < Double.valueOf(loanDetBean.getMin_loan_money())) {
                    loanString = CommonUtil.formatDouble(loanDetBean.getMin_loan_money());

                } else if (Double.valueOf(loanString) > Double.valueOf(loanDetBean.getMax_loan_money())) {
                    loanString = CommonUtil.formatDouble(loanDetBean.getMax_loan_money());
                }
                loanString = CommonUtil.formatDouble(loanString);
                loanMoneyEd.setText(loanString);
                loanMoneyEd.clearFocus();
                loadCompute();
                Log.e("zwj", "..键盘隐藏");
            }
        });
        titlebarRange = CommonUtil.dip2px(this, 80);
        titleTxRange = (int) (titlebarRange * 0.3);
        //饼状图
        mPieChart = (PieChart) findViewById(R.id.pie_chart);
        initPieChart();
        loanMoneyEd = (EditText) findViewById(R.id.loan_money_edit);
        loanMoneyEd.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.toString().contains(".")) {
                    if (s.toString().startsWith(".")) {
                        loanMoneyEd.setText(s.toString().replaceFirst(".", ""));
                    } else if (s.length() - 1 - s.toString().indexOf(".") > 2) {
                        s = s.toString().subSequence(0,
                                s.toString().indexOf(".") + 3);
                        loanMoneyEd.setText(s);
                        loanMoneyEd.setSelection(loanMoneyEd.getText().toString().trim().length());
                    }
                }

                if (s.toString().startsWith("0")
                        && s.toString().trim().length() > 1) {
                    if (!s.toString().substring(1, 2).equals(".")) {
                        loanMoneyEd.setText(s.toString().replaceFirst("0", ""));
                        loanMoneyEd.setSelection(loanMoneyEd.getText().toString().trim().length());
                    }
                }

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        editImg = (ImageView) findViewById(R.id.edit_img);
        loanImg = (RadiusImageView) findViewById(R.id.loan_img);
        loanName = (TextView) findViewById(R.id.loan_name);
        loanNote = (TextView) findViewById(R.id.loan_note);
        tagOne = (TextView) findViewById(R.id.tag_one);
        tagTwo = (TextView) findViewById(R.id.tag_two);
        tagThree = (TextView) findViewById(R.id.tag_three);
        moneyRate = (AutofitTextView) findViewById(R.id.money_rate);
        totalRate = (TextView) findViewById(R.id.total_rate);
        loanInfo = (TextView) findViewById(R.id.loan_info);
        loanRate = (TextView) findViewById(R.id.loan_rate);
        loanFee = (TextView) findViewById(R.id.loan_fee);
        loanOnetime = (TextView) findViewById(R.id.loan_onetime);
        titleBar = (RelativeLayout) findViewById(R.id.title_bar);
        titleCutLine = (View) findViewById(R.id.title_cut_line);
        back = (ImageView) findViewById(R.id.left_back);
        periodTv = (TextView) findViewById(R.id.period_tv);
        title = (TextView) findViewById(R.id.title);
        if (mLoan!=null&&mLoan.getLoan_product_name()!=null){
            title.setText(mLoan.getLoan_product_name());
        }
        mScrollView = (GradationScrollView) findViewById(R.id.scroll_view);
        mScrollView.setScrollViewListener(this);
        favoriteImg = (ImageView) findViewById(R.id.favorite_img);
        flowImg = (ImageView) findViewById(R.id.flow_img);
        flowImg.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, (int) (CommonUtil.getScreenWidth(this) / 6.35)));
        flowImg.setImageResource(R.drawable.bank_img_flow);
        conditRecyclerView = (RecyclerView) findViewById(R.id.condition_recycler_view);
        conditRecyclerView.setLayoutManager(new FullyLinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        mConditAdapter = new BankLoanConditionAdapter(this);
        mConditAdapter.setData(conditList);
        conditRecyclerView.setAdapter(mConditAdapter);
        mateRecyclerView = (RecyclerView) findViewById(R.id.material_recycler_view);
        mateRecyclerView.setLayoutManager(new FullyLinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        mMaterAdapter = new BankLoanMaterAdapter(this);
        mMaterAdapter.setData(materList);
        mateRecyclerView.setAdapter(mMaterAdapter);
        questRecyclerView = (RecyclerView) findViewById(R.id.question_recycler_view);
        questRecyclerView.setLayoutManager(new FullyLinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        mQuestAdapter = new LoanDetQuestionAdapter(this);
        mQuestAdapter.setData(questList);
        mQuestAdapter.setOnLoanQuestionListener(new LoanDetQuestionAdapter.OnLoanQuestionListener() {
            @Override
            public void onQuestionClick(QuestionBean bean) {
                Intent intent=new Intent(BankLoanDetialActivity.this,HelpQuestDetActivity.class);
                intent.putExtra("QUESTION",bean);
                startActivity(intent);
            }
        });
        questRecyclerView.setAdapter(mQuestAdapter);
    }

    @Override
    public void initBundle() {
        mLoan = (BankLoanBean) getIntent().getSerializableExtra("LOAN");
        needBack = getIntent().getBooleanExtra("NEED_BACK", false);

    }

    @Override
    public void initData() {
        if (mLoan != null) {
            getLoanDet();
            getQuestion();
        }

    }

    @Override
    public int getRootViewId() {
        return R.layout.activity_bank_loan_detial;
    }

    private void apply() {
        Map<String, String> params = new LinkedHashMap<String, String>();
        params.put("loan_id", mLoan.getLoan_product_id());
        params.put("province_id", SharePreUtil.getInstance(this).getLoactionParentId());
        params.put("city_id", SharePreUtil.getInstance(this).getLoactionAreaId());
        params.put("apply_money", loanMoneyEd.getText().toString().trim());
        params.put("apply_period", mPeriod.getPeriod_id());
        request(Contant.LOAN_APPLY, params, true, true);
    }

    private void getLoanDet() {
        mLoadingView.loading();
        Map<String, String> params = new LinkedHashMap<String, String>();
        params.put("loan_id", mLoan.getLoan_product_id());
        if (!request(Contant.LOAN_DETAILS, params, true, false)) {
            mLoadingView.fail();
        }
    }
    private void setShare(String platform) {
        Map<String, String> params = new LinkedHashMap<String, String>();
        if (platform.equals("WEIXIN")){
            params.put("share_type", "1");
        }else if (platform.equals("WEIXIN_CIRCLE")){
            params.put("share_type", "2");
        }else if (platform.equals("QQ")){
            params.put("share_type", "3");
        }
        params.put("loan_product_id", loanDetBean.getLoan_product_id());
        request(Contant.LOAN_SHARE_LOG, params, true, false);
    }
    private void setFavourite() {
        Map<String, String> params = new LinkedHashMap<String, String>();
        params.put("loan_id", loanDetBean.getLoan_product_id());
        request(Contant.LOAN_FAVORITE, params, true, true);
    }

    private void cancelFavourite() {
        Map<String, String> params = new LinkedHashMap<String, String>();
        params.put("loan_id", loanDetBean.getLoan_product_id());
        request(Contant.LOAN_FAVORITE_CANCEL, params, true, true);
    }

    private void getQuestion() {
        Map<String, String> params = new LinkedHashMap<String, String>();
        params.put("loan_agency_id", mLoan.getLoan_agency_id());
        request(Contant.LOAN_QUESTION, params, true, false);
    }

    private void setData() {
        if (loanDetBean == null)
            return;

        setPeriod();
        GlideUtil.getInstance().load(this, loanDetBean.getLoan_product_url(), loanImg, true);
        if (loanDetBean.getIs_favorite().equals("1")) {
            favoriteImg.setImageResource(R.drawable.cart_icon_collect);
        } else {
            favoriteImg.setImageResource(R.drawable.nav_icon_collect_sel);
        }
        title.setText(loanDetBean.getLoan_product_name());
        loanName.setText(loanDetBean.getLoan_product_name());
        loanNote.setText(loanDetBean.getLoan_product_outline());
        periodTv.setText(mPeriod.getPeriod_name());
        loanMoneyEd.setText(CommonUtil.formatDouble(loanDetBean.getMin_loan_money()));
        for (int i = 0; i < loanDetBean.getLoan_tag_str().size(); i++) {
            if (i == 0) {
                tagOne.setVisibility(View.VISIBLE);
                tagOne.setText(loanDetBean.getLoan_tag_str().get(0));
            } else if (i == 1) {
                tagTwo.setVisibility(View.VISIBLE);
                tagTwo.setText(loanDetBean.getLoan_tag_str().get(1));
            } else if (i == 2) {
                tagThree.setVisibility(View.VISIBLE);
                tagThree.setText(loanDetBean.getLoan_tag_str().get(2));
            }
        }
        if (loanDetBean.getMin_loan_money().equals(loanDetBean.getMax_loan_money())) {
            moneyRate.setText(loanDetBean.getMax_loan_money() + "万");
        } else {
            moneyRate.setText(loanDetBean.getMin_loan_money() + "万~" + loanDetBean.getMax_loan_money() + "万");
        }
        totalRate.setText(loanDetBean.getTotal_rate() + "%");
        if (loanDetBean.getLoan_apply_condition_str() != null && loanDetBean.getLoan_apply_condition_str().size() > 0) {
            conditList.clear();
            conditList.addAll(loanDetBean.getLoan_apply_condition_str());
            mConditAdapter.notifyDataSetChanged();
            findViewById(R.id.condition_lay).setVisibility(View.VISIBLE);
        } else {
            findViewById(R.id.condition_lay).setVisibility(View.GONE);
        }
        if (loanDetBean.getLoan_apply_material_str() != null && loanDetBean.getLoan_apply_material_str().size() > 0) {
            materList.clear();
            materList.addAll(loanDetBean.getLoan_apply_material_str());
            mMaterAdapter.notifyDataSetChanged();
            findViewById(R.id.material_lay).setVisibility(View.VISIBLE);
        } else {
            findViewById(R.id.material_lay).setVisibility(View.GONE);
        }
        loadCompute();


    }

    private void loadCompute() {
        if (loanDetBean == null)
            return;
        double loanMoney = Double.valueOf(loanMoneyEd.getText().toString().trim()) * 10000;
        String rate = ComputeUtil.bankLoanRate(loanMoney, Double.valueOf(loanDetBean.getRate_info().getMax_rate()), Integer.valueOf(mPeriod.getPeriod_id()));
        String fee = ComputeUtil.bankLoanFee(loanMoney, Double.valueOf(loanDetBean.getRate_info().getMax_fee()), Integer.valueOf(mPeriod.getPeriod_id()));
        String oneTime = ComputeUtil.bankLoanOneTime(loanMoney, Double.valueOf(loanDetBean.getNonrecurring_rate()));
        loanInfo.setText("贷款: " + loanMoneyEd.getText().toString().trim() + "万/" + mPeriod.getPeriod_name());
        loanRate.setText("利息: " + rate + "元（" + loanDetBean.getRate_info().getMax_rate() + "%/月)");
        loanFee.setText("费用: " + fee + "元（" + loanDetBean.getRate_info().getMax_fee() + "%/月)");
        loanOnetime.setText("一次性: " + oneTime + "元（" + loanDetBean.getNonrecurring_rate() + "%)");
        float total = (float) loanMoney + Float.valueOf(rate) + Float.valueOf(fee) + Float.valueOf(oneTime);
        float ratePie = Float.valueOf(rate) / total * 100;
        float feePie = Float.valueOf(fee) / total * 100;
        float oneTimePie = Float.valueOf(oneTime) / total * 100;
        float loanPie = 100 - ratePie - feePie - oneTimePie;
        showPie(loanPie, ratePie, feePie, oneTimePie);
//        loanInfo.setText();
    }

    private void initPieChart() {
        // 设置饼图是否接收点击事件，默认为true
        mPieChart.setTouchEnabled(false);
        mPieChart.setUsePercentValues(true);
        mPieChart.getDescription().setEnabled(false);
        mPieChart.setExtraOffsets(0, 0, 0, 0);
        mPieChart.setDragDecelerationFrictionCoef(0.95f);
        //设置中间文件
        mPieChart.setCenterText("");
        mPieChart.setDrawCenterText(false);

        mPieChart.setDrawHoleEnabled(true);
        //设置中间圆盘的颜色
        mPieChart.setHoleColor(getResources().getColor(R.color.transparent));

        mPieChart.setTransparentCircleColor(getResources().getColor(R.color.blue));
        mPieChart.setTransparentCircleAlpha(110);
        //设置中间圆盘的半径,值为所占饼图的百分比
        mPieChart.setHoleRadius(60f);
        //设置中间透明圈的半径,值为所占饼图的百分比
        mPieChart.setTransparentCircleRadius(60f);
        //起始角度
        mPieChart.setRotationAngle(-90);
        // 触摸旋转
        mPieChart.setRotationEnabled(false);
        mPieChart.setHighlightPerTapEnabled(true);
        //变化监听
        mPieChart.setOnChartValueSelectedListener(this);
        mPieChart.setDrawSliceText(false);
        mPieChart.highlightValues(null);
        //设置数据

        //设置比例图
        Legend l = mPieChart.getLegend();
        l.setEnabled(false);
        //刷新

        // 输入标签样式
//        mPieChart.setEntryLabelColor(getResources().getColor(R.color.blue));
//        mPieChart.setEntryLabelTextSize(12f);
    }

    private void showPie(float loan, float rate, float fee, float oneTime) {
        if (mPieChart == null)
            return;
        mPieChart.setData(getPieData(loan, rate, fee, oneTime));
        mPieChart.invalidate();
        mPieChart.animateY(1000, Easing.EasingOption.EaseInOutQuad);
    }

    private PieData getPieData(float i, float j, float m, float n) {
        //模拟数据
        ArrayList<PieEntry> entries = new ArrayList<PieEntry>();
        entries.add(new PieEntry(i, ""));
        entries.add(new PieEntry(j, ""));
        entries.add(new PieEntry(m, ""));
        entries.add(new PieEntry(n, ""));
        PieDataSet dataSet = new PieDataSet(entries, "");
        //设置各个饼状图之间的距离
        dataSet.setSliceSpace(0f);
        // 部分区域被选中时多出的长度
        dataSet.setSelectionShift(0f);

        //数据和颜色
        ArrayList<Integer> colors = new ArrayList<Integer>();
        colors.add(getResources().getColor(R.color.blue));
        colors.add(getResources().getColor(R.color.orange));
        colors.add(getResources().getColor(R.color.red));
        colors.add(getResources().getColor(R.color.green));
        dataSet.setColors(colors);
        PieData data = new PieData(dataSet);
        data.setValueFormatter(new PercentFormatter());
        data.setValueTextSize(11f);
        data.setValueTextColor(getResources().getColor(R.color.transparent));
        return data;
    }

    @Override
    public void onValueSelected(Entry e, Highlight h) {

    }

    @Override
    public void onNothingSelected() {

    }

    private void initPeriodDialog() {
        mPeriodDialog = new PeriodDialog(this, periodList, new PeriodDialog.OnRefundReasonListener() {
            @Override
            public void onCancel() {

            }

            @Override
            public void onSelect(PeriodBean period) {
                if (period != null) {
                    mPeriod = period;
                    periodTv.setText(period.getPeriod_name());
                    loadCompute();
                }

            }
        });

    }

    @Override
    public void onResponse(ResponseInfo responseInfo) {
        if (hasDestroy())
            return;
        super.onResponse(responseInfo);
        if (responseInfo.url.equals(Contant.LOAN_DETAILS)) {
            if (responseInfo.isRequestOk) {
                try {
                    loanDetBean = JSON.parseObject(responseInfo.content, BankLoanDetBean.class);
                    Log.e("zwj", loanDetBean.toString());
                    if (loanDetBean != null) {
                        setData();
                        mLoadingView.finish();
                    } else {
                        mLoadingView.fail();
                    }
                } catch (Exception e) {
                    Log.e("zwj", e.toString());
                    mLoadingView.fail();
                }
            } else {
                mLoadingView.fail();
            }
        } else if (responseInfo.url.equals(Contant.LOAN_QUESTION)) {
            if (responseInfo.isRequestOk) {
                try {
                    BankLoanQuestListBean questionBean = JSON.parseObject(responseInfo.content, BankLoanQuestListBean.class);
                    if (questionBean != null && questionBean.getLoan_question_list() != null && questionBean.getLoan_question_list().size() > 0) {
                        questList.clear();
                        questList.addAll(questionBean.getLoan_question_list());
                        mQuestAdapter.notifyDataSetChanged();
                        findViewById(R.id.question_lay).setVisibility(View.VISIBLE);
                    } else {
                        findViewById(R.id.question_lay).setVisibility(View.GONE);

                    }

                } catch (Exception e) {

                }
            } else {

            }
        } else if (responseInfo.url.equals(Contant.LOAN_FAVORITE)) {
            if (responseInfo.isRequestOk) {
                showToast("已收藏");
                favoriteImg.setImageResource(R.drawable.nav_icon_collect_sel);
                loanDetBean.setIs_favorite("2");
            }
        } else if (responseInfo.url.equals(Contant.LOAN_FAVORITE_CANCEL)) {
            if (responseInfo.isRequestOk) {
                showToast("已取消收藏");
                favoriteImg.setImageResource(R.drawable.cart_icon_collect);
                loanDetBean.setIs_favorite("1");
            }
        } else if (responseInfo.url.equals(Contant.LOAN_APPLY)) {
            if (responseInfo.isRequestOk) {
                try {
                    BankLoanApplyBean bean = JSON.parseObject(responseInfo.content, BankLoanApplyBean.class);
                    Intent materIntent = new Intent(this, BankLoanMaterTwoActivity.class);
                    materIntent.putExtra("BANK_LOAN", loanDetBean);
                    materIntent.putExtra("APPLY_MONEY", responseInfo.params.get("apply_money"));
                    materIntent.putExtra("APPLY_PERIOD", responseInfo.params.get("apply_period"));
                    if (bean != null && bean.getLoan_apply_id() != null) {
                        materIntent.putExtra("APPLY_ID", bean.getLoan_apply_id());
                    }
                    startActivity(materIntent);
                } catch (Exception e) {

                }
            }
        }
    }

    private void setPeriod() {
        if (loanDetBean == null)
            return;
        periodList.clear();
        int minPeriod = Integer.valueOf(loanDetBean.getMin_period());
        int maxPeriod = Integer.valueOf(loanDetBean.getMax_period());
        int size = maxPeriod - minPeriod + 1;
        PeriodBean period;
        for (int i = 0; i < size; i++) {
            period = new PeriodBean();
            period.setPeriod_id(minPeriod + i + "");
            period.setPeriod_name(minPeriod + i + "个月");
            periodList.add(period);
        }
        if (periodList.size() == 0) {
            period = new PeriodBean();
            period.setPeriod_id("0");
            period.setPeriod_name("0个月");
            periodList.add(period);
        }
        mPeriod = periodList.get(0);
    }

    private void share() {
        UmShare share = new UmShare(this, new ShareResultListener() {
            @Override
            public void onStart(String platform) {
                setShare(platform);
            }

            @Override
            public void onSuccess(String platform) {
            }

            @Override
            public void onCancel(String platform) {
            }

            @Override
            public void onError(String platform, Throwable t) {
            }
        });
        if (loanDetBean.getLoan_product_url() != null && !loanDetBean.getLoan_product_url().equals("")) {
            share.setImage(loanDetBean.getLoan_product_url());
        } else {
            share.setImage(R.mipmap.app_icon);
        }
        share.setText("普融信贷超市—全网唯一全额贴息互联网金融超市，日均贴息10万元。");
        share.setTitle("普融—中国中小企业普惠金融O2O模式领导者");
        if (loanDetBean.getShare_url() != null && loanDetBean.getShare_url().startsWith("http")) {
            share.setTargetUrl(loanDetBean.getShare_url());
        } else {
            share.setTargetUrl("http://www.purong.com/");
        }
        share.setPlatform(new SharePlatform(SHARE_MEDIA.WEIXIN), new SharePlatform(SHARE_MEDIA.WEIXIN_CIRCLE), new SharePlatform(SHARE_MEDIA.QQ));
        share.share();
    }

    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.share:
                if (Build.VERSION.SDK_INT >= 23) {
                    checkPermission();
                } else {
                    share();
                }

                break;
            case R.id.favorite:
                if (loanDetBean != null && loanDetBean.getIs_favorite().equals("1")) {
                    setFavourite();
                } else {
                    cancelFavourite();
                }
                break;
            case R.id.edit_lay:
                if (!loanMoneyEd.hasFocus())
                    loanMoneyEd.requestFocus();
                loanMoneyEd.setSelection(loanMoneyEd.getText().toString().trim().length());
                InputMethodManager imm = (InputMethodManager) loanMoneyEd.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.toggleSoftInput(0, InputMethodManager.SHOW_FORCED);
                break;
            case R.id.apply:
                if (loanDetBean == null)
                    return;
                String loanString = loanMoneyEd.getText().toString().trim();
                if (loanString.endsWith("."))
                    loanString = loanString.replaceAll("\\.", "");
                if (loanString.equals("")){
                    showToast("请输入贷款金额");
                    return;
                }
                if (Double.valueOf(loanString) < Double.valueOf(loanDetBean.getMin_loan_money())
                        ||Double.valueOf(loanString) > Double.valueOf(loanDetBean.getMax_loan_money())){
                    showToast("贷款金额必须在额度范围内");
                    return;
                }
                if (PuRongApp.getLoginInfo(this) != null) {
                    apply();
                } else {
                    Intent materIntent = new Intent(this, BankLoanMaterOneActivity.class);
                    materIntent.putExtra("BANK_LOAN", loanDetBean);
                    materIntent.putExtra("MONEY", loanMoneyEd.getText().toString().trim());
                    materIntent.putExtra("PERIOD", mPeriod.getPeriod_id());
                    startActivity(materIntent);
                }

                break;
            case R.id.rate_det:
                if (loanDetBean != null) {
                    Intent rateIntent = new Intent(this, BankLoanRateActivity.class);
                    rateIntent.putExtra("LOAN_DET", loanDetBean);
                    startActivity(rateIntent);
                }

                break;
            case R.id.more_question:
                if (loanDetBean == null)
                    return;
                Intent intent = new Intent(this, LoanQuestionActivity.class);
                intent.putExtra("AGENCY_ID", loanDetBean.getLoan_agency_id());
                startActivity(intent);
                break;
            case R.id.load_period:
                if (mPeriodDialog == null) {
                    initPeriodDialog();
                    mPeriodDialog.show();
                } else {
                    mPeriodDialog.show();
                }
                break;
            case R.id.left_back:
                finish();
                break;
        }
    }

    @Override
    public void onScrollChanged(GradationScrollView scrollView, int x, int y, int oldx, int oldy) {
        if (y <= 0) {   //设置标题的背景颜色
            title.setTextColor(Color.argb((int) 255, 255, 255, 255));
            titleBar.setBackgroundColor(Color.argb((int) 0, 255, 255, 255));
            titleCutLine.setVisibility(View.GONE);
            back.setImageResource(R.drawable.icon_white_back);
        } else if (y > 0 && y <= titlebarRange) { //滑动距离小于banner图的高度时，设置背景和字体颜色颜色透明度渐变
            float scale = (float) y / titlebarRange;
            float alpha = (255 * scale);
            titleBar.setBackgroundColor(Color.argb((int) alpha, 255, 255, 255));
            if (y > titleTxRange) {
                title.setTextColor(Color.argb((int) 255, 0, 0, 0));
                titleCutLine.setVisibility(View.VISIBLE);
                back.setImageResource(R.drawable.icon_black_back);

            } else {
                title.setTextColor(Color.argb((int) 255, 255, 255, 255));
                titleCutLine.setVisibility(View.GONE);
                back.setImageResource(R.drawable.icon_white_back);

            }

        } else {    //滑动到banner下面设置普通颜色
            titleBar.setBackgroundColor(Color.argb((int) 255, 255, 255, 255));
            title.setTextColor(Color.argb((int) 255, 0, 0, 0));
            titleCutLine.setVisibility(View.VISIBLE);
            back.setImageResource(R.drawable.icon_black_back);

        }

    }

    @Override
    protected String[] getPermissions() {
        return PermissionConstant.PERMS_STORAGE;
    }

    @Override
    protected void doPermissinosSuc() {
        share();
    }
}
